<?php
/**
 * Created by Adon.
 * User: Adon
 * Date: 2017/7/1
 * Time: 16:52
 */

namespace app\modules\api\models;


use app\hejiang\ApiResponse;
use app\models\Setting;
use app\models\Share;
use app\models\User;
use Curl\Curl;

class LoginForm extends ApiModel
{
    public $wechat_app;

    public $code;
    public $user_info;
    public $encrypted_data;
    public $iv;
    public $signature;

    public $store_id;

    public function rules()
    {
        return [
            [['wechat_app', 'code', 'user_info', 'encrypted_data', 'iv', 'signature',], 'required'],
        ];
    }

    public function login()
    {


        if (!$this->validate()) return $this->errorResponse;
        $res = $this->getOpenid($this->code);
        if (!$res || empty($res['openid'])) {
            return new ApiResponse(1,'获取用户OpenId失败',$res);
        }

        $ip = $this->get_real_ip();
        file_put_contents("/tmp/login.log",$ip."-".$this->user_info.PHP_EOL,8);
        $data  = json_decode($this->user_info,true);
        $data['openId'] = $res['openid'];

        if($data['avatarUrl'] &&  strpos($data['avatarUrl'] ,"mmhead")) {
            return new ApiResponse(1,'登录失败!',[]);
        }

//        $session_key = $res['session_key'];
//        require __DIR__ . '/wxbdc/WXBizDataCrypt.php';
//        $pc = new \WXBizDataCrypt($this->wechat_app->app_id, $session_key);
//        $errCode = $pc->decryptData($this->encrypted_data, $this->iv, $data);
//        if($errCode)   return new ApiResponse(1,'登录失败',$errCode);

        $user = User::findOne(['wechat_open_id' => $data['openId'], 'store_id' => $this->store_id]);
        if (!$user) {
            $user = new User();
            $user->type = 1;
            $user->username = $data['openId'];
            $user->password = \Yii::$app->security->generatePasswordHash(\Yii::$app->security->generateRandomString(), 5);
            $user->auth_key = \Yii::$app->security->generateRandomString();
            $user->access_token = \Yii::$app->security->generateRandomString();
            $user->addtime = time();
            $user->gender = $data['gender'];
            $user->is_delete = 0;
            $user->wechat_open_id = $data['openId'];
            $user->wechat_union_id = isset($data['unionId']) ? $data['unionId'] : '';
            //$user->nickname = $data['nickName'];
            $user->nickname = preg_replace('/[\xf0-\xf7].{3}/', '', $data['nickName']);
            $user->avatar_url = $data['avatarUrl'] ? $data['avatarUrl'] : \Yii::$app->request->hostInfo . \Yii::$app->request->baseUrl . '/statics/images/avatar.png';
            $user->store_id = $this->store_id;
            $user->save();
            $same_user = User::find()->select('id')->where([
                'AND',
                [
                    'store_id' => $this->store_id,
                    'wechat_open_id' => $data['openId'],
                    'is_delete' => 0,
                ],
                ['<', 'id', $user->id],
            ])->one();
            if ($same_user) {
                $user->delete();
                $user = null;
                $user = $same_user;
            }
        } else {
            $user->nickname = preg_replace('/[\xf0-\xf7].{3}/', '', $data['nickName']);
            $user->avatar_url = $data['avatarUrl'];
            $user->gender = $data['gender'];
            $user->save();
        }
        $share = Share::findOne(['user_id' => $user->parent_id]);
        $share_user = User::findOne(['id' => $share->user_id]);
        $data = [
            'access_token' => $user->access_token,
            'nickname' => $user->nickname,
            'avatar_url' => $user->avatar_url,
            'is_distributor' => $user->is_distributor ? $user->is_distributor : 0,
            'parent' => $share->id ? ($share->name ? $share->name : $share_user->nickname) : '总店',
            'id' => $user->id,
            'is_clerk' => $user->is_clerk === null ? 0 :$user->is_clerk,
            'integral' => $user->integral === null ? 0 : $user->integral,
            'money' => $user->money === null ? 0 : $user->money
        ];
        return new ApiResponse(0,'success',$data);
    }


    private function getOpenid($code)
    {
        $api = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->wechat_app->app_id}&secret={$this->wechat_app->app_secret}&js_code={$code}&grant_type=authorization_code";
        $curl = new Curl();
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        $curl->get($api);
        $res = $curl->response;
        $res = json_decode($res, true);
        return $res;
    }

    public function get_real_ip()

    {

        $ip=FALSE;

        //客户端IP 或 NONE

        if(!empty($_SERVER["HTTP_CLIENT_IP"])){

            $ip = $_SERVER["HTTP_CLIENT_IP"];

        }

        //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空

        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {

            $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);

            if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }

            for ($i = 0; $i < count($ips); $i++) {

                if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {

                    $ip = $ips[$i];

                    break;

                }

            }

        }

        //客户端IP 或 (最后一个)代理服务器 IP

        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);

    }
}
